package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Motion;
import com.itheima.service.MotionBankService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/motionBank")
public class MotionBankController {
    @Reference
    private MotionBankService motionBankService;


    //添加
    @RequestMapping("/add")
    public Result add(@RequestBody Motion motion){
        try{
            motionBankService.add(motion);//发送请求
            return new Result(true, MessageConstant.ADD_MOTION_BANK_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_MOTION_BANK_FAIL);
        }
    }


    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return motionBankService.findPage(queryPageBean);
    }


    //文件上传（Excel）
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile){
        try {

            List<String[]> list = POIUtils.readExcel(excelFile);

            List<Motion> data = new ArrayList<>();

            if(list != null && list.size() > 0){
                for (String[] strings : list) {

                    String code = strings[1];
                    String name = strings[2];
                    String count = strings[6];
                    String date = strings[5];

                    Motion motion = new Motion(code,name,count,date);

                    data.add(motion);
                }
            }
            motionBankService.addAll(data);
            return new Result(true, MessageConstant.IMPORT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_FAIL);
        }
    }
}
